package com.banciyuan.bcywebview.biz.novel;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.SpaceApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.LoadingHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.Novel;
import de.greenrobot.daoexample.model.TagDetail;


/**
 * Created by hy on 2015/5/15.
 */
public class NovelFragment extends BaseLazyContainerFragment {

    private RequestQueue mQueue;
    private int page = 1;
    private PullToRefreshListView lv;
    private View mProgressbarView;
    private LoadingHelper mProgressbarHelper;
    private ListView refreshableView;
    private boolean loading = false;
    private boolean hasMore = true;
    private NovelAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.novel_layout, container, false);
        initProgressbar(rootView);
        initArgs();
        initUi(rootView);
        initAction();
        return rootView;
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(getActivity());
    }

    @Override
    protected void initProgressbar(View rootview) {
        mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new LoadingHelper(rootview);
        mProgressbarHelper.setActionCallbacks(new LoadingHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                hasMore = true;
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View rootview) {
        lv = (PullToRefreshListView) rootview.findViewById(R.id.refresh_lv);
        refreshableView = lv.getRefreshableView();

        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, UIUtils.dip2px(8, getActivity()));
        View view = new View(getActivity());
        view.setLayoutParams(layoutParams);
        refreshableView.addHeaderView(view);
    }

    @Override
    protected void initAction() {
        lv.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!loading && hasMore) {
                    loading = true;
                    page++;
                    initData();
                }
            }
        });
        lv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (!loading) {
                    loading = true;
                    hasMore = true;
                    page = 1;
                    initData();
                }
            }
        });
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (null == adapter) {
                    return;
                }
                Novel novel = null;
                i = i - 2;
                i = i <= 0 ? 0 : i;
                if (null != adapter) {
                    novel = (Novel) adapter.getItem(i);
                }
                if (null != novel) {
                    DetailDataHelper.gotoWriterDetail(getActivity(), novel.getRp_id(), novel.getWp_id(), false);
                }
            }
        });
    }

    private List<Novel> novels = new ArrayList<Novel>();

    @Override
    protected void initData() {
        loading = true;
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        paramsList.add(new BcyPair(HttpUtils.COMENT_SUB, "writer"));
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, page + ""));
        paramsList.add(new BcyPair(HttpUtils.LIMIT, "10"));

        final HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + SpaceApi.getZanlist();

        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                        JSONObject result = new JSONObject(s);
                        Gson gson = new Gson();
                        String data = result.getString(HttpUtils.UPLOAD_DATA);
                        List<Novel> tempList = gson.fromJson(data, new TypeToken<List<Novel>>() {
                        }.getType());
                        if (tempList.size() == 0) {
                            if (page == 1)
                                mProgressbarHelper.onNodata("", true);
                            loading = false;
                            hasMore = false;
                            lv.onRefreshComplete();
                        } else {
                            processFinalData(tempList);
                        }

                    } else {
                        mProgressbarHelper.onFailed();
                        lv.onRefreshComplete();
                        loading = false;
                    }
                } catch (Exception e) {
                    mProgressbarHelper.onFailed();
                    lv.onRefreshComplete();
                    loading = false;
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                lv.onRefreshComplete();
                mProgressbarHelper.onFailed();
                loading = false;
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, getActivity(), params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }

    private void processFinalData(List<Novel> tempList) {
        for (Novel novel : tempList) {
            if (!TextUtils.isEmpty(novel.getWork()))
                novel.getPost_tags().add(0, new TagDetail(novel.getWid(), novel.getWork(), novel.getWork()));
        }
        if (page == 1) {
            novels.clear();
        }
        novels.addAll(tempList);
        if (null == adapter) {
            adapter = new NovelAdapter(getActivity(), novels);
            refreshableView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        mProgressbarHelper.onSuccess();
        lv.onRefreshComplete();
        loading = false;
    }
}
